package logic

import (
	"2210a/vipshop/models/mysql"
	"2210a/vipshop/models/redisinit"
	"2210a/vipshop/pkg"
	"context"
	"fmt"

	"2210a/vipshop/vipshoprpc/internal/svc"
	"2210a/vipshop/vipshoprpc/vipshoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginUserLogic {
	return &LoginUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginUserLogic) LoginUser(in *vipshoprpc.LoginUserRequest) (*vipshoprpc.LoginUserResponse, error) {
	// todo: add your logic here and delete this line
	get := redisinit.Client.Get("captchalogin" + in.Mobile)
	if get.Val() != in.Captcha {
		return nil, fmt.Errorf("图形验证码获取失败")
	}
	cmd := redisinit.Client.Get("codelogin" + in.Mobile)
	if cmd.Val() != in.Code {
		return nil, fmt.Errorf("短信验证码获取失败")
	}
	var users mysql.Users
	mysql.Db.Debug().Where("mobile = ?", in.Mobile).Find(&users)
	if users.ID == 0 {
		return nil, fmt.Errorf("用户不存在，请重新注册")
	}
	if users.Password != pkg.Md5Encryption(in.Password) {
		return nil, fmt.Errorf("密码不一致")
	}
	redisinit.Client.Del("captchalogin" + in.Mobile)
	redisinit.Client.Del("codelogin" + in.Mobile)
	return &vipshoprpc.LoginUserResponse{Id: int64(users.ID)}, nil
}
